package com.netease.nie.base.utils;

import java.util.Collections;
import java.util.List;

import com.netease.nie.constants.CommonConstants;

/**
 * 分页工具类
 * @author KingsHunter
 * @createDate June 23rd,2016
 *
 */
public final class PageUtils {

	private static final int PAGE_SIZE = CommonConstants.PAGE_SIZE;
	
	private static int getPage(Integer page) {
		if (page == null)
			page = 1;
		
		if (page <= 0)
			page = 1;
		return page;
	}
	
	public static int getPageStartIndex(Integer page) {
		page = getPage(page);
		int pageStartIndex = (page - 1) * PAGE_SIZE;
		return pageStartIndex;
	}
	
	public static int getPageEndIndex(Integer page) {
		int pageStartIndex = getPageStartIndex(page);
		int pageEndIndex = pageStartIndex + PAGE_SIZE;
		return pageEndIndex;
	}
	
	public static int getPageStartIndex(Integer page, Integer pageSize) {
		page = getPage(page);
		int pageStartIndex = (page - 1) * pageSize;
		return pageStartIndex;
	}
	
	public static int getPageEndIndex(Integer page, Integer pageSize) {
		int pageStartIndex = getPageStartIndex(page, pageSize);
		int pageEndIndex = pageStartIndex + pageSize;
		return pageEndIndex;
	}
	
	/**
     * 分割数组
     * 
     * @param list 数组
     * @param page 页码
     * @param pageSize 每页数据大小
     * @return
     */
    public static <T> List<T> getPageListByPage(List<T> list, Integer page, Integer pageSize) {
        if (list == null || list.isEmpty())
            return Collections.emptyList();
        if (page == null || page <= 0)
            page = 1;
        if (pageSize == null || pageSize <= 0)
            pageSize = 10;
        Integer total = list.size();
        Integer fromIndex = (page - 1) * pageSize;
        Integer toIndex = fromIndex + pageSize;
        if (fromIndex >= total)
            return Collections.emptyList();
        if (toIndex > total)
            toIndex = total;
        return list.subList(fromIndex, toIndex);
    }
    
    /**
     * 分割数组
     * @param list
     * @param pageStartIndex
     * @param pageEndIndex
     * @return
     */
    public static <T> List<T> getPageListByIndex(List<T> list, Integer pageStartIndex, Integer pageEndIndex) {
    	if (list == null || list.isEmpty())
    		return Collections.emptyList();
    	Integer total = list.size();
    	if (pageStartIndex == null || pageStartIndex < 0)
    		pageStartIndex = 0;
    	if (pageEndIndex == null || pageEndIndex < 0) {
    		if (total > 10)
    			pageEndIndex = 10;
    		else 
    			pageEndIndex = total;
    	}
    	if (pageStartIndex > pageEndIndex)
    		return Collections.emptyList();
    	if (pageStartIndex >= total)
    		return Collections.emptyList();
    	if (pageEndIndex > total)
    		pageEndIndex = total;
    	
    	return list.subList(pageStartIndex, pageEndIndex);
    }
    
}
